package m3f.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.jblas.DoubleMatrix;

public class DenseMatrixWriter {
	
	private static void writeMatrix(DoubleMatrix matrix, BufferedWriter writer)
	throws IOException {
		int rows = matrix.rows;
		int cols = matrix.columns;
		for(int i = 0; i < rows; i++){
			for(int j = 0; j < cols; j++){
				writer.write(matrix.get(i, j) + " ");
			}
			writer.write("\n");
		}
	}
	
	public static void writeMatrix(DoubleMatrix matrix, String filename, boolean transpose){
		try{
			FileWriter fWriter = new FileWriter(filename);
			BufferedWriter writer = new BufferedWriter(fWriter);
			if(!transpose){
				writeMatrix(matrix, writer);
			} else {
				writeTanspose(matrix, writer);
			}
			writer.close();
		}catch(IOException ex){
			ex.printStackTrace();
		}
	}
	
	private static void writeTanspose(DoubleMatrix matrix, BufferedWriter writer)
	throws IOException {
		int rows = matrix.rows;
		int cols = matrix.columns;
		for(int j = 0; j < cols; j++){
			for(int i = 0; i < rows; i++){
				writer.write(matrix.get(i, j) + " ");
			}
			writer.write("\n");
		}
	}
	
	BufferedWriter writer;
	
	public DenseMatrixWriter(String file){
		try{
			FileWriter fWriter = new FileWriter(file);
			writer = new BufferedWriter(fWriter);
		}catch(IOException ex){
			System.err.println("The file " + file + " cannot be opened for writing.");
			ex.printStackTrace();
		}
	}
	
	public void appendMatrix(DoubleMatrix matrix, boolean transpose){
		try{
			if(!transpose){
				writeMatrix(matrix, writer);
			}else{
				writeTanspose(matrix, writer);
			}
		}catch(IOException ex){
			System.err.println("Error appending a matrix");
			ex.printStackTrace();
		}
	}
	
	public void close(){
		try{
			writer.close();
		}catch(IOException ex){
			ex.printStackTrace();
		}
		writer = null;
	}
}
